package com.intel.factorytest.activity;

import java.lang.reflect.Method;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.telephony.TelephonyManager;

import com.android.internal.telephony.ITelephony;
import com.intel.factorytest.cfparser.ConfigFileParseUtil;
import com.intel.factorytest.cfparser.concrete.AConfigFileParser;
import com.intel.factorytest.cfparser.concrete.PropertiesConfParser;
import com.intel.factorytest.util.PropertiesUtil;

public class CallTest1 extends BaseActivity {

    private static final int REQ_CODE_CALL = 1;
    private static final String PHONENUMBER = "CallPhoneNumber";
    private static final String PHONENUMBER_DEF = "18682488760";
    
    private static final int sRetryTimes = 3;
    private int retryCounter = 0;
    
    private TelephonyManager mTelephonyMgr;
    private String mPhoneNumber = PHONENUMBER_DEF;
    
    private long call_start_timestamp;
    private long call_end_timestamp;
    
    // call timeout
    private int timeout = 2; // unit: sec
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTelephonyMgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        
        if (isSystemTest) mPhoneNumber = getPhoneNumber();
        call(mPhoneNumber);
    }
    
    private void call(String phoneNumber) {
        call_start_timestamp = System.currentTimeMillis();
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
        // startActivity(intent);
        startActivityForResult(intent, REQ_CODE_CALL);
        System.out.println("tangjun CallTest startCallActivity expense time " + (System.currentTimeMillis() - call_start_timestamp));
    }
    
    private String getPhoneNumber() {
        PropertiesConfParser parser = (PropertiesConfParser) ConfigFileParseUtil.getConfParserConcrete(this, AConfigFileParser.EXTENSION_PROPERTISE);
        PropertiesUtil properties = parser.getProperties(isPcba);
        return  properties.getProperty(PHONENUMBER, PHONENUMBER_DEF);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("tangjun CallTest onActivityResult requestCode = " + requestCode + " ,resultCode = " + resultCode);
        
        call_end_timestamp = System.currentTimeMillis();
        long elapse = call_end_timestamp - call_start_timestamp;
        System.out.println("tangjun CallTest call elapse = " + elapse + " milliseconds");
        if (elapse < (timeout + 1) * 1000) {// 未接通
            is_pass = false;
            if (retryCounter < sRetryTimes) {
                System.out.println("tangjun CallTest retry Call times=" + (++retryCounter));
                
                call(mPhoneNumber);
                
                retryCounter++;
            } else {
                System.out.println("tangjun CallTest retry over!");
                endCall(0);
            }
        } else {
            is_pass = true;
            endCall(0);
        }
    }
    
    @Override
    public void finish() {
        tc.setTestResult(is_pass);
        super.finish();
    }
    
    
    private void endCall(int afterSeconds) {
        if (afterSeconds < 0) afterSeconds = 1;
        
        System.out.println("tangjun: CallTest enter endCall()");
        ITelephony iTelephony = getITelephony();
        System.out.println("tangjun: CallTest itelephony=" + iTelephony);
        if (iTelephony != null) {
            while (afterSeconds > 0) {
                //Toast.makeText(getApplicationContext(), afterSeconds + "'s 后，通话将自动关闭！", Toast.LENGTH_SHORT).show(); // 有问题！！！
                System.out.println("tangjun CallTest " + afterSeconds + "'s 后，通话将自动关闭！");
                try {
                    Thread.sleep(1000);
                    afterSeconds--;
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            /*
            try {
                iTelephony.endCall();
                finish();
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            */
        } else {
            System.out.println("tangjun: CallTest itelephony is null");
        }
    }
    
    private ITelephony getITelephony() {
        TelephonyManager mTelephonyManager = (TelephonyManager) this.getApplicationContext().getSystemService(TELEPHONY_SERVICE);
        Class<TelephonyManager> c = TelephonyManager.class;
        Method getITelephonyMethod = null;
        try {
            getITelephonyMethod = c.getDeclaredMethod("getITelephony", (Class[]) null);
            getITelephonyMethod.setAccessible(true);
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        ITelephony iTelephony = null;
        try {
            iTelephony = (ITelephony) getITelephonyMethod.invoke(mTelephonyManager, (Object[]) null);
            return iTelephony;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return iTelephony;
    }

}
